package oop.db;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

/**
 * @author cumeo89
 *
 */
public class Database {

	private static final Database INSTANCE = new Database();
	
	public static Database get() {
		return INSTANCE;
	}

	private MysqlDataSource dataSource = null;
	
	public Database() {
		try {
			Class.forName("com.mysql.jdbc.Driver");
			dataSource = new MysqlDataSource();
			dataSource.setCharacterEncoding("UTF-8");
			dataSource.setUrl("jdbc:mysql://localhost:3306/tracnghiem");
			dataSource.setUser("root");
			dataSource.setPassword("root");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

	public int count(String sql) throws SQLException {
		Connection conn = null;
		Statement stmt = null;
		ResultSet rs = null;
		try {
			conn = getConnection();
			stmt = conn.createStatement();
			rs = stmt.executeQuery(sql);
			rs.next();
			return rs.getInt(1);
		} finally {
			if (rs != null) rs.close();
			if (stmt != null) stmt.close();
			if (conn != null) conn.close();
		}
	}

	public Connection getConnection() throws SQLException {
		return dataSource.getConnection();
	}
}